package com.eeepay.eeepay_v2.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.eeepay.eeepay_v2.BuildConfig;
import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.eeepay_v2.enc.EncRSA;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.AppUpdateUtil;
import com.eeepay.eeepay_v2.util.BtnStyleUtil;
import com.eeepay.v2_library.util.CheckPermissionUtil;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.eeepay_v2.view.InputMethodRelativeLayout;
import com.eeepay.v2_library.dialog.CustomDialog;
import com.eeepay.v2_library.dialog.DialogUtil;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABRegUtil;
import com.tencent.tinker.lib.service.PatchResult;
import com.tencent.tinker.lib.util.TinkerLog;
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals;
import com.tinkerpatch.sdk.TinkerPatch;
import com.tinkerpatch.sdk.tinker.callback.ResultCallBack;

import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.LoginApiServiceGrpc;
import cn.eeepay.api.grpc.nano.LoginProto;
import cn.jpush.android.api.JPushInterface;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2016/3/29.
 * 登录界面   这里支持手机号和邮箱登陆
 */
public class LoginActivity extends ABBaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener,InputMethodRelativeLayout.OnSizeChangedListenner {
    private static final int APP_INFO = 1;
    private static final int LOGIN = 2;
    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };
    private EditText phoneEt, passEt;
    private Button loginBtn;
    private TextView findPassTv;//找回密码
    private CheckBox visiblePsdCb;//密码可见
    private ImageView delAllImage;

    private String phone, password;

    private EditListener editListener;

    private String registerID ;//极光生成的id

    private InputMethodRelativeLayout loginpage;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }
    @Override
    protected void initWidget() {
        UserInfo.removeUserInfo();//清空数据，以防出现混乱
//        setPermission();
        loginBtn = getViewById(R.id.btn_login_confirm);
        loginpage = getViewById(R.id.loginpage);
        loginpage.setOnSizeChangedListenner(this);

        findPassTv = getViewById(R.id.tv_login_retrieve);
        visiblePsdCb = getViewById(R.id.cb_login_psdVisible);
        delAllImage = getViewById(R.id.iv_del_all);
        phoneEt = getViewById(R.id.et_login_phone);
        passEt = getViewById(R.id.et_login_password);
        if (bundle != null) {
            phone = bundle.getString("phone");
            phoneEt.setText(phone);
        }
        String lastPhone = SPUtils.getString(Constant.LOGIN_PHONE);
        if (!TextUtils.isEmpty(lastPhone)) {
            phoneEt.setText(lastPhone);
        }
        //add by zhuangzeqin 2017年4月18日10:55:12 填充密码
        String psw = SPUtils.getString(Constant.LOGIN_PASS);
        if (!TextUtils.isEmpty(psw)) {
            passEt.setText(psw);
            BtnStyleUtil.settingBtnStyle(mContext, loginBtn);
        } else {
            /** update zhuangzeqin 2017年4月13日12:12:48 样式修改**/
            BtnStyleUtil.inintBtnDefaultStyle(mContext, loginBtn);
        }
        // add by zhuangzeqin 2017年4月18日11:20:24 统一获取 登录手机号和密码
        phone = phoneEt.getText().toString().trim();
        password = passEt.getText().toString().trim();
        sendHttpRequest(APP_INFO);

        registerID = JPushInterface.getRegistrationID(mContext);
    }

    @Override
    protected void eventOnClick() {

        loginBtn.setOnClickListener(this);
        findPassTv.setOnClickListener(this);

        visiblePsdCb.setOnCheckedChangeListener(this);

        editListener = new EditListener();
//        phoneEt.setInputType(InputType.TYPE_CLASS_PHONE);
        phoneEt.addTextChangedListener(editListener);
        passEt.addTextChangedListener(editListener);
        delAllImage.setOnClickListener(this);

        phoneEt.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    delAllImage.setVisibility(View.VISIBLE);
                } else {
                    // 此处为失去焦点时的处理内容
                    delAllImage.setVisibility(View.GONE);
                }
            }
        });
        passEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("#*apptype*#".equals(s.toString())) {
                    BtnStyleUtil.settingBtnStyle(mContext, loginBtn);
                }
            }
        });
    }

    /**
     * test方法，获取app信息,add by zw 20161019
     */
    public boolean getAppType(String pwd) {
        if ("#*apptype*#".equals(pwd)) {

            Intent intent = new Intent(LoginActivity.this,
                    TestUpdateIPAct.class);
            startActivity(intent);
            finish();
            return true;
        }
        return false;
    }

    /**
     * add by zhuangzeqin 2017年8月1日15:57:13 初始化TinkerPath
     */
    private void initTankerPath() {
        if (BuildConfig.TINKER_ENABLE) {
            //immediately 为 true, 每次强制访问服务器更新
            TinkerPatch.with().fetchPatchUpdate(true);
            TinkerPatch.with().setPatchResultCallback(new ResultCallBack() {
                @Override
                public void onPatchResult(final PatchResult patchResult) {
                    if (patchResult == null) {
                        return;
                    }
                    TinkerLog.w("LoginActivity", "request PatchResult :" + patchResult.toString());
                    if (patchResult.isSuccess)
                    {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String patchVersion = patchResult.patchVersion;
                                TinkerLog.w("LoginActivity", "request patchVersion :" + patchVersion);
                                showTinkerPatchDialog();
                            }
                        });

                    }
                }
            });
        }
    }

    /**
     * 显示温馨提示语
     * 升级补丁包更新完成
       请重启您的应用
     */
    CustomDialog PatchDialog =null;
    private void showTinkerPatchDialog() {
        if (PatchDialog == null) {
            PatchDialog = DialogUtil.getSingleCustomDialog(mContext, "温馨提醒", "升级补丁包更新完成\n请重启您的应用.", "确  定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PatchDialog.cancel();
                    ShareTinkerInternals.killAllOtherProcess(getApplicationContext());
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
        }
        if (mContext != null && !isFinishing() && !PatchDialog.isShowing()) {
            PatchDialog.show();
        }
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        try {
                            LoginApiServiceGrpc.LoginApiServiceBlockingStub stub = LoginApiServiceGrpc
                                    .newBlockingStub(channel)
                                    .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                            switch (taskId) {
                                case LOGIN:
                                    LoginProto.LoginRequest request = new LoginProto.LoginRequest();
                                    try {
                                        request.userName = phone;
                                        request.userPwd = EncRSA.EncPass(password);
                                        request.teamId = ConfigPorperties.getInstance().getTeamId();
                                        //新增参数； 为了方便集成极光推送的功能
                                        request.deviceId = registerID;
                                        request.osType ="1"; //设备类型 1:android 2：ios
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        return null;
                                    }
                                    LoginProto.LoginResponse response = stub.login(request);
                                    return response;
                                case APP_INFO:
                                    LoginProto.CheckVersionReq req = new LoginProto.CheckVersionReq();
                                    req.appNo = ConfigPorperties.getInstance().getAppNo();
                                    req.platform = "0";
                                    req.version = ConfigPorperties.getInstance().getVersionName();
                                    LogUtils.d("versionName = " + req.version);
                                    LoginProto.CheckVersionRes res = stub.checkVersion(req);
                                    return res;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;

                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (result == null) {
                            showToast("网络错误");
                            return;
                        }
                        switch (taskId) {
                            case LOGIN:
                                LoginProto.LoginResponse response = (LoginProto.LoginResponse) result;
                                if (!response.resMsg.status) {
                                    showToast(response.resMsg.msg);
                                    return;
                                }
                                UserInfo.removeUserInfo();//清空数据，以防出现混乱
                                //用户信息
                                UserInfo userInfo = UserInfo.getInstance();
                                userInfo.setUserNo(response.loginMsg.userId);
                                userInfo.setUserName(response.loginMsg.userName);
                                userInfo.setPhone(response.loginMsg.phone);
                                userInfo.setAgentName(response.loginMsg.agentName);
                                userInfo.setAgentNo(response.loginMsg.agentNo);
                                userInfo.setRole(response.loginMsg.manage);
                                userInfo.setAgentNode(response.loginMsg.agentNode);
                                userInfo.setOneAgentNo(response.loginMsg.oneAgentNo);
                                userInfo.setAgentLevel(response.loginMsg.agentLevel);
                                userInfo.setHandle(response.loginMsg.handle);
//                        userInfo.setAuthorities(response.loginMsg.authorities);
                                LogUtils.d("userInfo = " + userInfo.toString());
                                userInfo.saveUserInfo();
                                SPUtils.saveString(Constant.LOGIN_PHONE, phone);//保存登陆手机号，下次进入自动填充
                                SPUtils.saveString(Constant.LOGIN_PASS, password);//保存登陆密码，下次进入自动填充
                                MyApplication.getInstance().isLogin = true;
                                goActivity(MainActivity.class, bundle);
                                LoginActivity.this.finish();
                                break;
                            case APP_INFO:
                                LoginProto.CheckVersionRes res = (LoginProto.CheckVersionRes) result;
                                if (!res.resMsg.status) {
                                    showToast(res.resMsg.msg);
                                    return;
                                }
                                AppUpdateUtil.downFlag = res.version.downFlag;
                                AppUpdateUtil.downloadUrl = res.version.appUrl;
                                AppUpdateUtil.verDesc = res.version.verDesc;//更新内容描述
                                setPermission();
                                break;
                        }

                    }
                });
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_login_confirm:
                boolean appType = getAppType(password);
                if (appType) return;
                if (ABRegUtil.isRegiest(phone, ABRegUtil.REG_PHONE_CHINA)
                        || ABRegUtil.isRegiest(phone, ABRegUtil.REG_EMAIL)) {
                    sendHttpRequest(LOGIN);
                } else {
                    showToast("请输入正确手机号或邮箱");
                }
                break;
            case R.id.tv_login_retrieve://找回密码
                goActivity(AuthCodeActivity.class, bundle);
                break;
            case R.id.iv_del_all:
                phoneEt.setText("");
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            //如果选中，显示密码
            passEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //否则隐藏密码
            passEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    private boolean isUpDataApp() {
        if (!TextUtils.isEmpty(AppUpdateUtil.downFlag)
                && !"0".equals(AppUpdateUtil.downFlag)) {
            AppUpdateUtil.doNewVersionUpdate(mContext);
            return true;
        }
        return false;
    }

    /**
     * 在Activity中实现OnSizeChangedListener，原理是设置该布局的paddingTop属性来控制子View的偏移
     * @param flag
     * @param w
     * @param h
     */
    @Override
    public void onSizeChange(boolean flag, int w, int h) {
        if(flag){//键盘弹出时
            Rect r = new Rect();
            //获取当前界面可视部分
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                LoginActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            }
            //获取屏幕的高度
            int screenHeight =  LoginActivity.this.getWindow().getDecorView().getRootView().getHeight();
            //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
            int heightDifference = screenHeight - r.bottom;
            Log.d("Keyboard Size", "Size: " + heightDifference);
            loginpage.setPadding(0, -(loginBtn.getBottom()-heightDifference), 0, 0);

        }else{ //键盘隐藏时
            loginpage.setPadding(0, 0, 0, 0);
        }
    }


    class EditListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            phone = phoneEt.getText().toString().trim();
            password = passEt.getText().toString().trim();
            if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(password)) {
                BtnStyleUtil.settingBtnStyle(mContext, loginBtn);
            } else {
                BtnStyleUtil.inintBtnDefaultStyle(mContext, loginBtn);
            }
        }
    }

    private void setPermission() {
        try {
            CheckPermissionUtil.listener = new CheckPermissionUtil.onPermissionListener() {
                @Override
                public void onSuccess() {
                    //这里暂时不处理
                    if (isUpDataApp()) {// 需要更新
                        dismissProgressDialog();
                    } else {
                        dismissProgressDialog();
                        //add by zhuangzeqin 2017年8月1日17:06:00 新增热修复补丁包，
                        // 先判断是否有全量升级； 如果有则优先全量升级，如果没有；在考虑热补丁修复
                        initTankerPath();

                    }
                }

                @Override
                public void onFailure() {
                    Toast.makeText(mContext, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
                }
            };

            CheckPermissionUtil.checkPermission(this, PERMISSIONS, getViewById(R.id.ll_login), Constant.RESULTCODE_100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Constant.RESULTCODE_100) {
            CheckPermissionUtil.verifyPermissions(grantResults);
        }
    }

}
